from flask_wtf import Form
from wtforms import StringField, SubmitField, TextAreaField, BooleanField, SelectField
from wtforms.validators import Required, Length, Email, Regexp, ValidationError
from flask_pagedown.fields import PageDownField
from ..models import Role, User


# 表单类
class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('提交')
# 资料编辑表单
class EditProfileForm(Form):
    name = StringField('姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('自我介绍')
    submit = SubmitField('提交')

# 管理员使用的资料编辑表单
class EditProfileAdminForm(Form):
    email = StringField('邮箱', validators=[Required(), Length(0, 64), Email()])
    username = StringField('用户名', validators=[Required(), Length(0, 64), Regexp('^[\\u4E00-\\u9FA5A-Za-z][\\u4E00-\\u9FA5A-Za-z0-9]+$',
                                                                                0, '用户名必须是字母数字点或者下划线')])
    confirmed = BooleanField('已认证的')
    role = SelectField('角色', coerce=int)
    name = StringField('姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('自我介绍')
    submit = SubmitField('提交')
    def __init__(self, user, *args, **kwargs):
        super(EditProfileAdminForm, self).__init__(*args, **kwargs)
        self.role.choices = [(role.role_id, role.role_name)
                             for role in Role.query.order_by(Role.role_name).all()]
        self.user = user
    def validate_email(self, field):
        if field.data != self.user.email and User.query.filter_by(email=field.data).first():
            raise ValidationError('邮箱已经被注册')
    def validate_username(self, field):
        if field.data != self.user.username and User.query.filter_by(username=field.data).first():
            raise ValidationError('用户名已经被注册')

# 按钮，表单
class PostForm(Form):
    body = PageDownField('写点什么吧...', validators=[Required()])
    submit = SubmitField('写完提交')
